package com.sxt.generate.generate;

import com.sxt.generate.configuration.Configuration;
import com.sxt.generate.configuration.ConfigurationParser;
import com.sxt.generate.table.Clazz;
import com.sxt.generate.table.Table;
import com.sxt.generate.table.TableFactory;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * @ClassName: Configuration
 * @Description:Configuration
 * @version:v1.0.0
 * @author: haning
 * @date:
 */
public class Generator {

    public static void generate() {
        ConfigurationParser.parse();
        generateFile(getTableInfos());
    }

    public static void generateFile(List<Table> tables) {
        for (Table table : tables) {
            ExcuteFile ef = new ExcuteFile(table);
            ef.generateFile(table);
        }
    }

    public static List<Table> getTableInfos() {

        String driver = Configuration.getJdbc().get("jdbc.driverClassName");
        String url = Configuration.getJdbc().get("jdbc.url");
        String username = Configuration.getJdbc().get("jdbc.username");
        String password = Configuration.getJdbc().get("jdbc.password");


        String sourceDir = Configuration.getTemplate().get("source.dir");
        String resourceDir = Configuration.getTemplate().get("resource.dir");
        String templateDir = Configuration.getTemplate().get("template.dir");
        String override_ = Configuration.getTemplate().get("override");

        assert StringUtils.isNotBlank(driver) : "driver can't read";
        assert StringUtils.isNotBlank(url) : "url can't read";

        List<Map<String, String>> generates = Configuration.getGenerates();
        List<Table> tables = new ArrayList<Table>();
        for (Map<String, String> generateMap : generates) {
            String tableName = generateMap.get("tableName");
            String className = generateMap.get("className");
            String basePackage = generateMap.get("basePackage");
            assert StringUtils.isNotBlank(tableName) : "tableName can't read";
            Table table = new TableFactory().getTable(tableName, driver, url, username, password);
            if (table != null) {
                table.setClassName(className);
                Clazz clazz = new Clazz();
                clazz.setSourceDir(sourceDir);
                clazz.setResourceDir(resourceDir);
                clazz.setTemplateDir(templateDir);
                clazz.setOverride_(override_);
                clazz.setClassName(className);
                clazz.setBasePackage(basePackage);
                table.setClazz(clazz);
                tables.add(table);
            }

        }
        return tables;

    }
}
